package com.avic.rong.course.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.product.CommentListActivity;
import com.avic.rong.activity.product.DetailProductActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.activity.product.PDFReaderActivity;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.course.activity.otherActivity.PeiXunBaoMingActivity;
import com.avic.rong.course.activity.otherActivity.PeiXunClassMuLuActivity;
import com.avic.rong.course.activity.otherActivity.PeiXunDownDataActivity;
import com.avic.rong.course.activity.otherActivity.PeiXunIntroductionActivity;
import com.avic.rong.course.activity.otherActivity.PeiXunPingLunActivity;
import com.avic.rong.course.activity.otherActivity.VideoPlayerActivity;
import com.avic.rong.payUtil.JavaPayUtil;
import com.avic.rong.payUtil.PayVo;
import com.avic.rong.questionOrAnswer.DialogShare;
import com.avic.rong.questionOrAnswer.ShareUtilCallBack;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.userOrder.activity.BankPayActivity;
import com.avic.rong.userOrder.activity.OrderDetailsPXActivity;
import com.avic.rong.userOrder.activity.PayAgreenActivity;
import com.avic.rong.userOrder.activity.PaySucceedActivity;
import com.avic.rong.userOrder.activity.ShopPayActivity;
import com.avic.rong.userOrder.adapter.PayWayAdapter;
import com.avic.rong.userOrder.api.OrderSubmitPXApi;
import com.avic.rong.userOrder.api.PaySubmitPXApi;
import com.avic.rong.userOrder.api.ToPayPXApi;
import com.avic.rong.userOrder.bean.PayWayBean;
import com.avic.rong.userOrder.bean.PeiXunOrderBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.MoneyShowUtils;
import com.avic.rong.utils.NetResponseListener;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.SmartHttp;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.ScrollWebView;
import com.avic.rong.wedgit.StringUtil;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.OnReturnValue;

public class CourseDetailActivity extends RxAppCompatActivity implements ScrollWebView.OnScrollChangeListener, ShareUtilCallBack, BGASwipeBackHelper.Delegate {


    public static final String ARG_SKUID = "skuId";
    public static final String ARG_FIRST_IMAGE = "first_image";
    public static final String ARG_VIDEO_NAME = "name";

    public static final Integer AnimationDuration = 1000;
    @BindView(R.id.webview)
    ScrollWebView webview;
    @BindView(R.id.tv_ok)
    ImageView tvOk;
    @BindView(R.id.tv_share)
    ImageView tvShare;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;

    @BindView(R.id.rl_root_bottom)
    RelativeLayout rl_root_bottom;
    @BindView(R.id.peixun_FrameLayout)
    FrameLayout peixunFrameLayout;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;

    @BindView(R.id.shangpin)
    TextView shangpin;
    @BindView(R.id.pingjia)
    TextView pingjia;
    @BindView(R.id.xiangqing)
    TextView xiangqing;
    @BindView(R.id.tuijian)
    TextView tuijian;
    @BindView(R.id.img_underline)
    ImageView img_underline;

    private String firstImageUrl = ConstantsUtils.EMPTY_STR;
    private String videoName = ConstantsUtils.EMPTY_STR;


    private String skuIdStr = "";


    private DialogShare dialogShare;


    private float startX = 0f;
    private boolean ishade = false;


    private boolean isClickTab = false;

    private JavaPayUtil javaPayUtil;

    private boolean isClickBuy = false;


    public static String ORDER_ID = "order_id";
    public static String ORDER_SN = "order_sn";
    private int COMMENT_FORCODE = 6;
    private int payId = -1;
    private PopupWindow popupWindow;
    private boolean isAgreement = true;//勾选用户协议
    private int orderType = -1;
    private PayWayAdapter payWayAdapter;

    private List<PayWayBean.PaymentListBean> paymentList = new ArrayList<>();
    private double shouldPayTotal;
    private String orderNumber;

    private static String filePath;
    private Context context;
    private View popView;
    private BGASwipeBackHelper mSwipeBackHelper;
    private String urlString;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_course);

        ButterKnife.bind(this);


        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.color_2D3038));

        loading_layout.setStatus(LoadingLayout.SUCCESS);

        startX = shangpin.getX();

        skuIdStr = getIntent().getStringExtra(ARG_SKUID);
        firstImageUrl = getIntent().getStringExtra(ARG_FIRST_IMAGE);
        videoName = getIntent().getStringExtra(ARG_VIDEO_NAME);
        webview.addJavascriptObject(this, null);
        webview.setListener(this);
        webview.setHorizontalScrollBarEnabled(false);
        webview.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        urlString = AppUtils.BASE_URL + "study/" + skuIdStr;
        Log.e("wcx", "onCreate: " + urlString);
        webview.loadUrl(urlString);

        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);

    }

    @Override
    protected void onResume() {
        webview.loadUrl(urlString);
        super.onResume();
    }

    //异步获取token
    @JavascriptInterface
    public void loginAsyn(Object msg, CompletionHandler<String> handler) {

        String s = msg.toString();
        if (s.equals("1")) {
            if (StringUtil.isEmpty(SharedPreferencesUtil.getLoginToken())) {
                Intent intent = new Intent(CourseDetailActivity.this, LoginPhoneActivity.class);
                intent.putExtra("come_from", "CourseDetailActivity");
                startActivity(intent);
            } else {
                handler.complete(SharedPreferencesUtil.getLoginToken());
            }
        } else {
            String login_token = SharedPreferencesUtil.getLoginToken();
            if (StringUtil.isEmpty(login_token)) {
                handler.complete("");
            } else {
                handler.complete(login_token);
            }
        }
    }

    //培训课时目录
    @JavascriptInterface
    public void courseListAsyn(Object msg, CompletionHandler<String> handler) {

        if (msg != null) {
            String tempString = msg.toString();
//            tempString = "04013";
            String courseId = tempString.substring(1);
            String type = tempString.substring(0, 1);
            Logger.e("cjx", "s.charAt(0)" + tempString.charAt(0));
            startActivity(PeiXunClassMuLuActivity.getIntent(CourseDetailActivity.this, courseId, type, firstImageUrl));
        }
        handler.complete("ddd");
    }


    //商品页
    @JavascriptInterface
    public void goodPageAsyn(Object msg, CompletionHandler<String> handler) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast toast = Toast.makeText(CourseDetailActivity.this, msg + "", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
                startActivity(DetailProductActivity.getIntent(CourseDetailActivity.this, msg.toString()));
                handler.complete("dddd");
            }
        });
    }

    //提交订单
    @JavascriptInterface
    public void studyPayAsyn(Object msg, CompletionHandler<String> handler) {
        if (!isClickBuy) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                Toast toast = Toast.makeText(CourseDetailActivity.this, msg + "", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
//                Intent intent = new Intent(CourseDetailActivity.this, PeiXunIntroductionActivity.class);
//                intent.putExtra(COURSESID,msg.toString());
//                Log.e(TAG, "run: author"+msg.toString());
//                startActivity(intent);
//                startActivity(DetailProductActivity.getIntent(context, msg.toString()));
                    handler.complete("dddd");
                }
            });
            Log.e("cjx", "peixun 支付：" + msg.toString());
            String type1 = msg.toString().substring(0, 1);
            orderType = Integer.parseInt(type1);
            if (SharedPreferencesUtil.isLogin()) {
                String s = msg.toString();
                String type = s.substring(0, 1);
                String courseId = s.substring(1);
                Log.e("cjx", "courseId:" + courseId);
                Log.e("cjx", "type:" + type);
                Map<String, String> map = new HashMap<>();
                map.put("courseId", courseId);
                map.put("orderType", type);
                map.put("token", SharedPreferencesUtil.getLoginToken());
                map.put("amount", "1");
                // TODO: 2019/8/20  调用培训支付接口完成
                OrderSubmitPXApi classMuLuApi = new OrderSubmitPXApi(this, simpleOnNextListener);
                classMuLuApi.setCache(false);
                classMuLuApi.setMap(map);
                HttpManager.getInstance().doHttpDeal(classMuLuApi);
            } else {
                Intent intent = new Intent(CourseDetailActivity.this, LoginPhoneActivity.class);
                intent.putExtra("come_from", "CourseDetailActivity");
                startActivity(intent);
            }
            isClickBuy = true;
        }


    }

    //获取课时目录列表数据监听
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(CourseDetailActivity.this, subjects.getMsg());
                Log.e("cjx", subjects.getMsg());
                return;
            }
            PeiXunOrderBean bean = (PeiXunOrderBean) subjects.getData();
            orderNumber = bean.getOrderNumber();
//            Log.e(TAG, "onNext: orderNumber" + orderNumber);
            shouldPayTotal = bean.getShouldPayTotal();
            toPayPX(5, orderNumber);
            Log.e("cjx", "调用培训支付接口完成" + subjects.getResult());
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "培训课时目录列表数据：" + e.getMessage());
        }
    };


    private void toPayPX(int orderType, String orderSn) {

        if (!SharedPreferencesUtil.getLoginToken().isEmpty()) {

            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(CourseDetailActivity.this, "没有获取到订单编号");
                return;
            }
            this.orderNumber = orderSn;
            this.orderType = orderType;
//            paramsBody.put("orderId", orderId+"");
            paramsBody.put("token", SharedPreferencesUtil.getLoginToken());

            //获取支付方式
            final ToPayPXApi toPayPXApi = new ToPayPXApi(this, simpleOnNextListenerPayWayPX);
            toPayPXApi.setCache(false);
            toPayPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(toPayPXApi);


        }
    }

    //培训获取支付方式
    HttpOnNextListener simpleOnNextListenerPayWayPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(CourseDetailActivity.this, subjects.getMsg());
                return;
            }

            PayWayBean data = (PayWayBean) subjects.getData();
            paymentList.addAll(data.getPaymentList());
            //选择支付
            selectPay(data);


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };


    private void selectPay(PayWayBean data) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.select_pay_way_layout, null);
        RelativeLayout rl_close = (RelativeLayout) inflate.findViewById(R.id.rl_close);
//        final ImageView chat_btn = (ImageView) inflate.findViewById(R.id.chat_btn);
//        final ImageView ali_btn = (ImageView) inflate.findViewById(R.id.ali_btn);
//        final ImageView zhuanzhang_btn = (ImageView) inflate.findViewById(R.id.zhuanzhang_btn);
//        final ImageView yue_btn = (ImageView) inflate.findViewById(R.id.yue_btn);
//        final ImageView shop_pay_btn = (ImageView) inflate.findViewById(R.id.shop_pay_btn);
        RecyclerView recy_list = inflate.findViewById(R.id.recy_list);
        final ImageView iv_agree = (ImageView) inflate.findViewById(R.id.iv_agree);
        final TextView tv_submit_order = (TextView) inflate.findViewById(R.id.tv_submit_order);
        final TextView tv_pay_agreen = (TextView) inflate.findViewById(R.id.tv_pay_agreen);
//        final TextView tv_order_price = (TextView) inflate.findViewById(R.id.tv_order_price);
        final EditText et_use_yue = (EditText) inflate.findViewById(R.id.et_use_yue);
        final LinearLayout ll_use_yue = (LinearLayout) inflate.findViewById(R.id.ll_use_yue);
        if (TextUtils.isEmpty(shouldPayTotal + "")) return;
        tv_submit_order.setText("确认付款 ¥" + MoneyShowUtils.dealNumber(shouldPayTotal + ""));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CourseDetailActivity.this);
        recy_list.setLayoutManager(linearLayoutManager);
        payWayAdapter = new PayWayAdapter(CourseDetailActivity.this, paymentList);
        recy_list.setAdapter(payWayAdapter);
        payWayAdapter.setOrderType(5);

        //只有ordertype==4才有余额支付
        if (orderType != 5) {
            if (orderType == 4) {
                ll_use_yue.setVisibility(View.VISIBLE);
            } else {
                ll_use_yue.setVisibility(View.GONE);
            }
        } else {
            ll_use_yue.setVisibility(View.GONE);
        }


        payWayAdapter.setYueMoney(data.getUserMoney());
        payWayAdapter.setOrderPrice(shouldPayTotal + "");
        payWayAdapter.notifyDataSetChanged();


        iv_agree.setSelected(isAgreement);
//        chat_btn.setRJCPSelected(true);
        coursePop(CourseDetailActivity.this, inflate);
        //关闭按钮
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogCustom.showDoubleDialog(CourseDetailActivity.this, "", "确认放弃付款？", "确认离开", "继续支付", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {

                    }

                    @Override
                    public void leftButtonClicked() {

                        Intent intent = new Intent(CourseDetailActivity.this, OrderDetailsPXActivity.class);
                        intent.putExtra(ORDER_SN, orderNumber + "");

                        startActivityForResult(intent, COMMENT_FORCODE);
                        popupWindow.dismiss();
                    }
                });
            }
        });

        //列表点击事件
        payWayAdapter.setOnClickItem(new PayWayAdapter.OnClickItem() {
            @Override
            public void OnClickListion(View view, int postion) {
                if (paymentList != null && paymentList.size() > 0) {
                    payId = paymentList.get(postion).getPayId();
                }
                payWayAdapter.setmSelectedPos(postion);
                payWayAdapter.notifyDataSetChanged();
            }
        });
        //支付协议
        tv_pay_agreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CourseDetailActivity.this, PayAgreenActivity.class);
                startActivity(intent);
            }
        });
//        chat_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(true);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//                Toast.makeText(OrderConfirmActivity.this, "点击了", Toast.LENGTH_SHORT).show();
//            }
//        });
//        ali_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(true);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        zhuanzhang_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(true);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        yue_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(true);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        shop_pay_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(true);
//            }
//        });
        //同意条款
        iv_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAgreement = !isAgreement;
                iv_agree.setSelected(isAgreement);
            }
        });
        //付款提交
        tv_submit_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String useYue = et_use_yue.getText().toString().trim();
                String submitMoney = tv_submit_order.getText().toString().trim();
                submitMoney = submitMoney.replace("确认付款 ¥", "");
                if (Double.parseDouble(submitMoney) <= 0) {
                    if (payId == 2 || payId == 3 || payId == 4 || payId == 6) {
                        ToastTools.showLongToast(CourseDetailActivity.this, "支付金额为0，请选择余额支付");
                        return;
                    }

                }
                if (!iv_agree.isSelected()) {
                    ToastTools.showLongToast(CourseDetailActivity.this, "同意条款才能进行支付");
                    return;
                } else if (payId != -1 && payId == 5) {
                    if (!TextUtils.isEmpty(useYue)) {
                        ToastTools.showLongToast(CourseDetailActivity.this, "选择余额支付后无需填写余额");
                        return;
                    }
                } else if (payId != -1 && payId != 5) {
                    if (!TextUtils.isEmpty(useYue) && !TextUtils.isEmpty(shouldPayTotal + "")) {
                        if (Double.parseDouble(useYue) > Double.parseDouble(shouldPayTotal + "")) {
                            ToastTools.showLongToast(CourseDetailActivity.this, "您选择了混合的支付方式，请填写正确的金额");
                            return;
                        }
                    }

                }


                if (payWayAdapter.getBalancePayId() == 5 || payId == 5) {
                    paySubmitPX(submitMoney);
                } else {
                    paySubmitPX(useYue);

                }

            }
        });


    }


    //讲师列表
    @JavascriptInterface
    public void authorListAsyn(Object msg, CompletionHandler<String> handler) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast toast = Toast.makeText(CourseDetailActivity.this, msg + "", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
                Intent intent = new Intent(CourseDetailActivity.this, PeiXunIntroductionActivity.class);
                intent.putExtra(PeiXunClassMuLuActivity.COURSESID, msg.toString());
                //Log.e(TAG, "run: author" + msg.toString());
                startActivity(intent);
                handler.complete("dddd");
            }
        });
    }

    //相关资料
    @JavascriptInterface
    public void courseFileListAsyn(Object msg, CompletionHandler<String> handler) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast toast = Toast.makeText(CourseDetailActivity.this, msg + "", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
                Intent intent = new Intent(CourseDetailActivity.this, PeiXunDownDataActivity.class);
                intent.putExtra(PeiXunClassMuLuActivity.COURSESID, msg.toString());
                //  Log.e(TAG, "run: down" + msg.toString());
                startActivity(intent);
                handler.complete("dddd");
            }
        });
    }

    private Handler Threadhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(CourseDetailActivity.this, "下载完成！\n文件存储路径:" + filePath, Toast.LENGTH_SHORT).show();
                Log.e("cjx", "path:" + filePath);
            }
        }
    };

    //相关资料列表条目点击
    @JavascriptInterface
    public void fileAsyn(Object msg, CompletionHandler<String> handler) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("url", "run: " + msg);
                String[] split = msg.toString().split("//");
                if (split != null && split.length > 0) {
                    String flieName = split[split.length - 1];
                    downLoad(msg.toString(), flieName, CourseDetailActivity.this, Threadhandler);
                    handler.complete("dddd");
                }
            }
        });
    }

    public static void downLoad(final String httpUrl, final String FileName, Context context, Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(httpUrl);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {
                            FileUtils fileUtils = new FileUtils();
                            fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));//指定文件保存路径，代码看下一步
                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                            }
                            handler.sendEmptyMessage(1);
                            Log.e("cjx", "下载完成");
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static class FileUtils {
        String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";

        public FileUtils() {
            File file = new File(path);
            /**
             *如果文件夹不存在就创建
             */
            if (!file.exists()) {
                file.mkdirs();
            }
        }

        /**
         * 创建一个文件
         *
         * @param FileName 文件名
         * @return
         */
        public File createFile(String FileName) {
            filePath = path + "/" + FileName;
            return new File(path, FileName);
        }
    }


    //头像-个人主页
    @JavascriptInterface
    public void rrAsyn(Object msg, CompletionHandler<String> handler) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast toast = Toast.makeText(CourseDetailActivity.this, msg + "", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
                Log.e("cjx", "头像-个人主页" + msg.toString());
                Intent intent = new Intent(CourseDetailActivity.this, PersonalHomeActivity.class);
                intent.putExtra("homeUserID", msg.toString());
                startActivity(intent);
                handler.complete("dddd");
            }
        });
    }

    //在线阅读
    @JavascriptInterface
    public void onlineReaderAsyn(Object msg, CompletionHandler<String> handler) {
//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
        if (!SharedPreferencesUtil.isLogin()) {
            Intent intent = new Intent(CourseDetailActivity.this, LoginPhoneActivity.class);
            intent.putExtra("come_from", "CourseDetailActivity");
            startActivity(intent);
        }


        String url = null;
        try {
            url = AppUtils.BASE_URL + "member/checkMemberService?token=" + URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        SmartHttp.getHttp(url, new NetResponseListener() {
            @Override
            public void sucListener(JSONObject response) {
                Logger.i("--------" + response.toString());
                String code = response.optString("code");
                if (ConstantsUtils.STATUS_REQUEST_ERROR_1001.equals(code)) {//开通会员
                    startActivity(CourseDetailActivity.getIntent(CourseDetailActivity.this, "288498", firstImageUrl, videoName));
                } else if (ConstantsUtils.STATUS_SUCCESS_0000.equals(code)) {//已开通会员
                    startActivity(PDFReaderActivity.getIntent(CourseDetailActivity.this, "GJB 9001C-2017"));
                }
            }

            @Override
            public void errListener(String error_msg) {

            }
        });


        handler.complete("usertoken");
    }


    //客服
    @JavascriptInterface
    public void cserviceAsyn(Object msg, CompletionHandler<String> handler) {

//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//            toast.setGravity(Gravity.CENTER, 0, 0);
//            toast.show();
        if (SharedPreferencesUtil.isLogin()) {
            startActivity(OnlineCServiceActivity.getIntent(this, SharedPreferencesUtil.getLoginToken()));
        } else {
            Intent intent = new Intent(CourseDetailActivity.this, LoginPhoneActivity.class);
            intent.putExtra("come_from", "CourseDetailActivity");
            startActivity(intent);
        }


        handler.complete(msg + " [ asyn call]");
    }

    //加入书架
//    @JavascriptInterface
//    public void joinStudyPlain(Object msg, CompletionHandler<String> handler) {
//
////        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
////            toast.setGravity(Gravity.CENTER, 0, 0);
////            toast.show();
//
//        if (SharedPreferencesUtil.isLogin()) {
//            String s = msg.toString();
//            String substring = s.substring(1);
//            new PeiXunBookShelfActivity().joinStudyPlain(substring);
//        } else {
//            Intent intent = new Intent(CourseDetailActivity.this, LoginPhoneActivity.class);
//            intent.putExtra("come_from", "CourseDetailActivity");
//            startActivity(intent);
//        }
//        handler.complete(msg + " [ asyn call]");
//    }

    //报名咨询
    @JavascriptInterface
    public void consultAsyn(Object msg, CompletionHandler<String> handler) {

//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//            toast.setGravity(Gravity.CENTER, 0, 0);
//            toast.show();
        startActivity(new Intent(this, PeiXunBaoMingActivity.class));
        handler.complete(msg + " [ asyn call]");
    }

    //播放
    @JavascriptInterface
    public void playAsyn(Object msg, CompletionHandler<String> handler) {
        if (SharedPreferencesUtil.isLogin()) {
//            Log.e("cjx", "videoPath:"+msg.toString());
//            Log.e("cjx", "firstImgPath:"+ConstantUtil.COURSE_IMAGE_URL+firstImageUrl);
//            Log.e("cjx", "name:"+videoName);
//            Intent intent = new Intent(context, VideoPlayerActivity.class);
//            intent.putExtra(VideoPlayerActivity.ARG_URL, msg.toString());
//            intent.putExtra(VideoPlayerActivity.ARG_IMAGE_URL, ConstantUtil.COURSE_IMAGE_URL+firstImageUrl);
//            intent.putExtra(VideoPlayerActivity.ARG_NAME,videoName);

            Log.e("cjx", "videoPath:" + msg.toString());
            Log.e("cjx", "firstImgPath:" + AppUtils.COURSE_IMAGE_URL + firstImageUrl);
            Log.e("cjx", "name:" + videoName);
            Intent intent = new Intent(CourseDetailActivity.this, VideoPlayerActivity.class);
            intent.putExtra(VideoPlayerActivity.ARG_URL, msg.toString());
            intent.putExtra(VideoPlayerActivity.ARG_IMAGE_URL, AppUtils.COURSE_IMAGE_URL + firstImageUrl);
            intent.putExtra(VideoPlayerActivity.ARG_NAME, videoName);
//        Log.e("cjx","msg::"+msg.toString());
            startActivity(intent);
            handler.complete(msg + " [ asyn call]");
        } else {
            ToastTools.showToast("登录后才可观看");
//            startActivity(new Intent(CourseDetailActivity.this, LoginPhoneActivity.class));
            startActivity(LoginPhoneActivity.getIntent(CourseDetailActivity.this, "CourseDetailActivity"));
        }


    }

    //查看全部评价
    @JavascriptInterface
    public void evaluateListAsyn(Object msg, CompletionHandler<String> handler) {

        Log.e("cjx", "evaluateListAsyn---------" + msg.toString());
        Intent intent = new Intent(CourseDetailActivity.this, PeiXunPingLunActivity.class);
        intent.putExtra(PeiXunClassMuLuActivity.COURSESID, msg.toString());
        startActivity(intent);
        handler.complete(msg + " [ asyn call]");
    }

    //去开通会员
    @JavascriptInterface
    public void goKaitongAsyn(Object msg, CompletionHandler<String> handler) {

//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
        startActivity(CourseDetailActivity.getIntent(CourseDetailActivity.this, "288498", firstImageUrl, videoName));

        handler.complete(msg + " [ asyn call]");
    }


    //评论查看全部
    @JavascriptInterface
    public void commentAllAsyn(Object msg, CompletionHandler<String> handler) {
//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse((String) msg);
        if (element.isJsonObject()) {
            JsonObject jsonElement = (JsonObject) element;
            Integer idValue = jsonElement.get("idValue").getAsInt();
            Integer commentType = jsonElement.get("commentType").getAsInt();
//            Log.e("===sku",skuStr);
            startActivity(CommentListActivity.getIntent(CourseDetailActivity.this, commentType, idValue));
        }


        handler.complete(msg + " [ asyn call]");
    }


    //查看
    @JavascriptInterface
    public void previewGoodDetailAsyn(Object msg, CompletionHandler<String> handler) {
//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
        String skuId = "";
        if (msg instanceof Integer) {
            skuId = String.valueOf(msg);
        } else if (msg instanceof String) {
            skuId = (String) msg;
        }
        startActivity(CourseDetailActivity.getIntent(CourseDetailActivity.this, skuId, firstImageUrl, videoName));

//        finish();
        handler.complete(msg + " [ asyn call]");
    }

    @OnClick({R.id.tv_share, R.id.tv_share_bottom})
    public void onShare() {

//        final Wang wang = new Wang("wang","1");

//        webView.callHandler("getUserIdTwo", new Object[]{new Gson().toJson(wang)}, new OnReturnValue<String>() {
//            @Override
//            public void onValue(String retValue) {
//                Toast toast = Toast.makeText(DetailProductActivity.this, "1111" + retValue, Toast.LENGTH_SHORT);
//                      toast.setGravity(Gravity.CENTER, 0, 0);
//                      toast.show();
//            }
//        });


        if (dialogShare == null) {
            dialogShare = new DialogShare(CourseDetailActivity.this, CourseDetailActivity.this);
        }

        String tempUrl = AppUtils.BASE_URL_H5 + "peixun/course/" + skuIdStr + ".html";
        dialogShare.showDialog("我在融融上发现了一份好的资料，想邀分享给你", videoName, tempUrl, firstImageUrl);
      /*  webview.callHandler("getGoodsNameAndImage", new OnReturnValue<Object>() {
            @Override
            public void onValue(Object retValue) {
                Log.e("course", "onValue: "+retValue.toString() );
                JsonParser parser = new JsonParser();
                JsonElement element = parser.parse((String) retValue);
                if (element.isJsonObject()) {
                    JsonObject jsonElement = (JsonObject) element;
                    String sdName = jsonElement.get("sdTopTitle").getAsString();
                    String sdImage = jsonElement.get("sdShopImg").getAsString();

                   // dialogShare.showDialog("我在融融上发现了一份好的资料，想邀分享给你", sdName, urlString, sdImage);
                }
               dialogShare.showDialog("我在融融上发现了一份好的资料，想邀分享给你", videoName, urlString, firstImageUrl);
            }
        });*/


    }


    float currentAlph = 0.0f;

    @Override
    public void onScrollchange(int y, int direction) {
        Log.e("course", "onScrollchange:  y" + y + "   direction: " + direction);


        if (y < 100) {
            currentAlph = y * 1.0f / 100;
            rlRoot.setAlpha(currentAlph);
//            Logger.i("----------------iii----" + currentAlph);
//            rl_top.getBackground().setAlpha((int)(currentAlph * 255));
            if (direction == 1) {
                if (y > 0) {
                    StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.color_1fc133));
                }
            } else {
                if (y == 0) {
                    StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.color_2D3038));
                }
                rl_root_bottom.setAlpha(1 - currentAlph);
            }
        } else {
            rlRoot.setAlpha(1.0f);
            rlRoot.setVisibility(View.VISIBLE);
        }
        isClickTab = false;
    }

    //H5定位
    @JavascriptInterface
    public void locationAsyn(Object msg, CompletionHandler<String> handler) {
//        Toast toast = Toast.makeText(DetailProductActivity.this, msg + "", Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        toast.show();
        if (msg != null) {
            if ("1".equals(msg)) {
                underlineAnimation22(shangpin);

            } else if ("3".equals(msg)) {
                underlineAnimation22(pingjia);

            } else if ("2".equals(msg)) {
                underlineAnimation22(xiangqing);

            } else if ("4".equals(msg)) {
                underlineAnimation22(tuijian);

            }
        }

        handler.complete(msg + " [ asyn call]");
    }

    //定位
    @OnClick({R.id.shangpin, R.id.pingjia, R.id.xiangqing, R.id.tuijian})
    public void onPosition(View view) {

        isClickTab = true;

        int viewId = view.getId();
        String currentPost = "1";
        switch (viewId) {
            case R.id.shangpin:
                currentPost = "1";
                break;
            case R.id.pingjia:
                currentPost = "2";
                break;
            case R.id.xiangqing:
                currentPost = "3";
                break;
            case R.id.tuijian:
                currentPost = "4";
                break;
        }


        webview.callHandler("pagePostion", new Object[]{currentPost}, new OnReturnValue<String>() {
            @Override
            public void onValue(String retValue) {

            }
        });
    }


    public void underlineAnimation22(final View view) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                float endX = view.getX();
                Animation animation = new TranslateAnimation(startX, endX, 0, 0);
                animation.setFillAfter(true);
                animation.setDuration(250);
                // 给图片添加动画
                img_underline.startAnimation(animation);
                startX = view.getX();
            }
        });
    }


    @OnClick({R.id.shangpin, R.id.pingjia, R.id.xiangqing, R.id.tuijian})
    public void underlineAnimation(View view) {

        float endX = view.getX();
        Animation animation = new TranslateAnimation(startX, endX, 0, 0);
        animation.setFillAfter(true);
        animation.setDuration(250);
        // 给图片添加动画
        img_underline.startAnimation(animation);
        startX = view.getX();
    }

    @OnClick({R.id.img_back, R.id.img_back_bottom})
    public void onBack() {
        onBackPressed();
    }

    @OnClick({R.id.tv_ok, R.id.tv_ok_bottom})
    public void OKClick() {
        showPopup(CourseDetailActivity.this, rl_root_bottom);
    }

    protected void showPopup(CourseDetailActivity baseActivity, View view) {
        commonPop(view);
        initListener(baseActivity);
    }

    ;

    /*
     * 功能直达蒙层
     * */
    private void commonPop(View view) {
        popView = LayoutInflater.from(this).inflate(R.layout.function_of_direct, null, false);
        popupWindow = new PopupWindow(popView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
       /* // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setClippingEnabled(false);
        //从上往下弹出动画效果
        popupWindow.setAnimationStyle(R.style.topPopupAnimation);
        popupWindow.showAtLocation(view, Gravity.TOP, 0, 0);
    }

    private void initListener(Context context) {
        ImageView img_close_pop = popView.findViewById(R.id.img_close_pop);
        Button bt_home = popView.findViewById(R.id.bt_home);
        Button bt_mall = popView.findViewById(R.id.bt_mall);
        Button bt_news = popView.findViewById(R.id.bt_news);
        Button bt_own = popView.findViewById(R.id.bt_own);
        Button bt_goods_car = popView.findViewById(R.id.bt_goods_car);
        Button bt_kefu = popView.findViewById(R.id.bt_kefu);

        img_close_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        bt_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new HomePageEvent());
                startActivity(goMain());
            }
        });
        bt_mall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new GoCartListEvent());
                startActivity(goMain());
            }
        });
        bt_news.setOnClickListener(new View.OnClickListener() {//消息
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new CartListReloadEvent());
                    startActivity(goMain());
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "CourseDetailActivity"));
                }
            }
        });
        bt_own.setOnClickListener(new View.OnClickListener() {//我的
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new MinePageEvent());
                    startActivity(goMain());
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "CourseDetailActivity"));
                }
            }
        });
        bt_goods_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                startActivity(ShoppingCarActivity.queryIntent(CourseDetailActivity.this));
            }
        });
        bt_kefu.setOnClickListener(new View.OnClickListener() {//客服
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    startActivity(OnlineCServiceActivity.getIntent(CourseDetailActivity.this, "123456"));
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "CourseDetailActivity"));
                }
            }
        });


    }


    public static Intent getIntent(Context context, String courseId, String firstImageUrl, String videoName) {
        Intent intent = new Intent(context, CourseDetailActivity.class);
        intent.putExtra(ARG_SKUID, courseId);
        intent.putExtra(ARG_VIDEO_NAME, videoName);
        intent.putExtra(ARG_FIRST_IMAGE, firstImageUrl);
        return intent;
    }


    @Override
    public void shareSuccess() {

    }

    @Override
    public void shareFailed() {

    }

    @Override
    public void shareCancel() {

    }


    private void coursePop(Context context, View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, false);
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        //从下往上弹出动画效果
        popupWindow.setAnimationStyle(R.style.bottomPopupAnimation);
        popupWindow.showAtLocation(findViewById(R.id.peixun_FrameLayout), Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }


    private void paySubmitPX(String useYue) {

        if (!SharedPreferencesUtil.getLoginToken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderNumber)) {
                ToastTools.showToast(CourseDetailActivity.this, "没有获取到支付ID");
                return;
            }
            paramsBody.put("orderNumber", orderNumber);
            paramsBody.put("token", SharedPreferencesUtil.getLoginToken());

            if (payWayAdapter.getBalancePayId() == -1 && payId == -1) {
                return;
            }
            paramsBody.put("payId", payId + "");
            //支付提交
            final PaySubmitPXApi paySubmitPXApi = new PaySubmitPXApi(this, simpleOnNextListenerPaySubmitPX);
            paySubmitPXApi.setCache(false);
            paySubmitPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(paySubmitPXApi);


        }

    }

    //培训支付提交
    HttpOnNextListener simpleOnNextListenerPaySubmitPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(CourseDetailActivity.this, subjects.getMsg());
                return;
            }
            popupWindow.dismiss();
            if ((PayVo) subjects.getData() != null) {
                final PayVo payVo = (PayVo) subjects.getData();
                if (javaPayUtil == null) {
                    javaPayUtil = new JavaPayUtil(CourseDetailActivity.this, new JavaPayUtil.PaySuccessCallBack() {
                        @Override
                        public void paySuccess() {
//                            Intent intent = new Intent();
//                            setResult(MEMBER_REFRESH, intent);
//                            finish();
//                            ToastTools.showToast(OrderConfirmActivity.this,"支付成功");
//                            new Intent(OrderConfirmActivity.this,)
                            if (TextUtils.isEmpty(orderNumber)) {
                                ToastTools.showToast(CourseDetailActivity.this, "没有获取到支付ID");
                                return;
                            }
                            //  pay_state  1  成功   2   失败
                            Intent intent = new Intent(CourseDetailActivity.this, PaySucceedActivity.class);
                            intent.putExtra("order_sn", orderNumber + "");
                            intent.putExtra("order_type", 5);
                            intent.putExtra("pay_state", 1 + "");
                            startActivity(intent);
                        }

                        @Override
                        public void expertPaySuccess(String consultType) {

                        }

                        @Override
                        public void payCancel() {
                            if (TextUtils.isEmpty(orderNumber)) {
                                ToastTools.showToast(CourseDetailActivity.this, "没有获取到支付ID");
                                return;
                            }
                            //  pay_state  1  成功   2   失败
                            Intent intent = new Intent(CourseDetailActivity.this, PaySucceedActivity.class);
                            intent.putExtra("order_sn", orderNumber + "");
                            intent.putExtra("order_type", 5);
                            intent.putExtra("pay_state", 2 + "");
                            startActivity(intent);
                        }
                    });
                }

                //orderType用来区分是否有余额支付
                if (orderType != -1) {
                    payVo.setOrderType(5);
                }
                //payId  2  微信支付   3     支付宝     4    银行汇款/转账     6   到店支付     5   余额支付
                if (payId == 2) {
                    javaPayUtil.payByWay(payVo, "WeChat");
                } else if (payId == 3) {
                    javaPayUtil.payByWay(payVo, "Alipay");
                } else if (payId == 4) {
                    Intent intent = new Intent(CourseDetailActivity.this, BankPayActivity.class);
//                    intent.putExtra("order_id", orderNumber + "");
                    intent.putExtra("order_sn", orderNumber + "");
                    intent.putExtra("orderType", 5 + "");
                    startActivity(intent);

                } else if (payWayAdapter.getBalancePayId() == 5 || payId == 5) {
                    if (TextUtils.isEmpty(orderNumber)) {
                        ToastTools.showToast(CourseDetailActivity.this, "没有获取到订单ID");
                        return;
                    }
                    Intent intent = new Intent(CourseDetailActivity.this, PaySucceedActivity.class);
                    intent.putExtra("order_sn", orderNumber + "");
                    intent.putExtra("order_type", 5);
                    startActivity(intent);
                } else if (payId == 6) {
                    Intent intent = new Intent(CourseDetailActivity.this, ShopPayActivity.class);
                    startActivity(intent);
                }

            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    public Intent goMain() {
        Intent intent = MainActivity.queryIntent(this);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return intent;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (dialogShare != null) {
            dialogShare.initActivityResultSsoHandler(requestCode, resultCode, data);
        }
    }
}
